/*
 * @Author: Penk
 * @LastEditors: Penk
 * @LastEditTime: 2022-04-30 23:51:52
 * @FilePath: \puppeteer-demo\scripts\script.js
 */

import chalk from "chalk";
import moment from "moment";
const log = console.log;
const error = chalk.bold.red;
const warning = chalk.hex("#FFA500"); // Orange color

import $excel from "./excel.js";
import $log from "./log.js";
const EMAIL = $excel.getEmail();

function myLog(...msg) {
  var temp = msg.join("");
  log(warning(moment().format("yyyy-MM-DD hh:mm:ss") + "：" + temp));
}

function myLog2(msg, color, isSave = true) {
  var ck = null;
  if (color) {
    if (color[0] == "#") {
      ck = chalk.hex(color);
    } else {
      ck = chalk.bold[color];
    }
  } else {
    ck = chalk.hex("#FFA500");
  }
  log(ck(moment().format("yyyy-MM-DD hh:mm:ss") + "：" + msg));
  isSave && saveLog(msg);
}

// 保存日志
function saveLog(msg) {
  var productNum = obj.getNotifyInfo().productNum || "已加载完毕";
  var fileName =
    moment().format("yyyy-MM-DD") + "-" + productNum + "-提醒插件日志";

  $log.saveLog(fileName, msg);
}

// 在浏览器中打印console
async function consoleWithChrome(msg) {
  await this.page.evaluate(() => console.log(msg));
}

function randomNum(minNum, maxNum) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * minNum + 1, 10);
      break;
    case 2:
      return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
      break;
    default:
      return 0;
      break;
  }
}

// 获取文本相关
async function getHandleByText() {
  let selector = "a";
  await page.$$eval(selector, (anchors) => {
    anchors.map((anchor) => {
      if (anchor.textContent == "target text") {
        anchor.click();
        return;
      }
    });
  });
}

var obj = {
  // 当前活动页面对象
  page: null,
  // 当前浏览器对象
  browser: null,
  // 判断程序是否在执行中，避免重复执行
  running: false,
  // excel 传过来的对象
  notifyInfo: null,
  // 一个型号页面刷新的计算
  account: 0,
  // 一个型号页面最大刷新数
  maxNum: 3,

  getNotifyInfo() {
    if (!this.notifyInfo || !this.notifyInfo.isRemind == "否") {
      this.notifyInfo = $excel.getFirstOne();
      this.account = 0;
      myLog2(`===========${this.notifyInfo.productNum}===========`);
    }
    return this.notifyInfo;
  },

  // 通知失败  如果超过最大数量怎么返回true
  async notifyError() {
    if (this.account < this.maxNum) {
      this.account++;
      myLog2(
        `型号${this.notifyInfo.productNum}第${this.account}次通知失败，即将刷新...`
      );
      return false;
    } else {
      myLog2(
        `型号${this.notifyInfo.productNum}通知已达到${this.maxNum + 1}次...`
      );
      let body = {
        ...this.notifyInfo,
      };
      body.isRemind = `失败${this.maxNum + 1}次`;
      let ret = $excel.setOneRemind(body);
      // 需要保存再清空
      myLog2(ret.msg);
      return true;
    }
  },

  // 通知成功
  async notifySuccess() {
    // 通知成功
    let body = {
      ...this.notifyInfo,
    };
    body.isRemind = "是";
    let ret = $excel.setOneRemind(body);
    // 需要保存再清空
    myLog2(ret.msg);
    this.notifyInfo = null;
  },

  // 初始化
  async init(page, browser) {
    this.page = page;
    this.browser = browser;
  },

  // 等待页面刷新
  async waitForNetworkidle2(timeout = 10000) {
    try {
      await this.page.waitForNavigation({
        timeout: timeout,
        waitUntil: "networkidle2",
      });
      myLog("networkidle2成功...");
    } catch (error) {
      myLog("networkidle2失败...");
    }
  },

  // 获取当前的URL
  async getUrl() {
    let href = "";
    // href = await this.page.evaluate(() => {
    //   return window.location.href;
    // });
    href = this.page.url();
    return href;
  },

  // 鼠标点击命令
  async mouseFn() {
    // 随机3-10 次
    var count = randomNum(2, 5);
    for (let i = 0; i < count; i++) {
      // 随机范围
      var x = randomNum(100, 500);
      var y = randomNum(100, 400);

      await this.page.mouse.move(x, y);
      await this.page.mouse.down({ button: middle });
      await this.page.mouse.up();
    }
  },

  // 首页
  async homePage() {
    myLog2("打开" + "首页" + "成功...");

    let notifyInfo = this.getNotifyInfo();
    if (!notifyInfo) {
      myLog2("通知完毕...", "blue", true);
      return;
    }
    console.log("notifyInfo:", notifyInfo);

    // ====================操作开始===================== //
    // 输入型号
    const modelInput = await this.page.waitForSelector(
      "#searchboxheader input"
    );
    await modelInput.focus(); //定位到搜索框
    await this.page.keyboard.type(notifyInfo.productNum);

    const [response] = await Promise.all([
      // this.page.waitForNavigation(waitOptions),
      // 模拟键盘“回车”键
      this.page.keyboard.press("Enter"),
    ]);
  },

  // 页面顶部配送区域
  async distributionArea() {
    var selector =
      "#tiResponsiveHeader > div.ti_p-responsiveHeader-top-bar > div.ti_p-responsiveHeader-top-bar-content > div.ti_p-responsiveHeader-top-llc > div.ti_p-responsiveHeader-llc-component.mod-shipto > ti-header-ship-to-selection > ti-dropdown-panel > div.ti-dropdown-panel-trigger.sc-ti-dropdown-panel.sc-ti-dropdown-panel-s > div.sc-ti-header-ship-to-selection > div > span";
    var areaBtn = await this.page.waitForSelector(selector);
    await this.page.waitForTimeout(1000);
    !!areaBtn && areaBtn.click();

    var selector2 =
      "#tiResponsiveHeader > div.ti_p-responsiveHeader-top-bar > div.ti_p-responsiveHeader-top-bar-content > div.ti_p-responsiveHeader-top-llc > div.ti_p-responsiveHeader-llc-component.mod-shipto > ti-header-ship-to-selection > ti-dropdown-panel > div.ti-dropdown-panel-content.sc-ti-dropdown-panel.sc-ti-dropdown-panel-s > div > div > div.ti-header-ship-to-selection-list-container.sc-ti-header-ship-to-selection > ul > li:nth-child(28) > a";
    var chinaBtn = await this.page.waitForSelector(selector2);
    await this.page.waitForTimeout(1000);
    !!chinaBtn && chinaBtn.click();
    myLog2("页面顶部配送区域完成...", "blue", true);
    await this.page.waitForTimeout(10000);
  },

  // 页面弹出配送地址和货币选择
  async configAddressAndCurrency() {
    myLog2("页面弹出配送地址和货币选择...", "green", true);
    await this.page.waitForSelector("#llc-cartpage-ship-to-country", {
      timeout: 3000,
    });
    await this.page.select("#llc-cartpage-ship-to-country", "China");
    var btn = await this.page.waitForSelector(
      "#llc-cartpage-ship-to-continue button"
    );
    !!btn && btn.click();
  },

  // 搜索首页
  async searchPage() {
    myLog2("打开" + "搜索首页" + "成功...");

    // ====================操作开始===================== //
    var selector =
      "#search > section > div > div.ti_p-col.u-padding-top-8.ti_search-result-container > div.search-extras-section > div > ti-opn-snapshot > ti-card > div > div > div > div.ti-opn-snapshot-opn-match-details.sc-ti-opn-snapshot > ti-opn-details > div > div > div.ti-opn-details-info.sc-ti-opn-details > ti-titled-description > div > h4 > div > a";
    var btn = await this.page.waitForSelector(selector, {
      timeout: 80000,
    });

    if (!!btn) {
      myLog2("点击了...");
      btn.click();
    } else {
      myLog2("搜索首页 型号按钮没有加载出来...");
      await this.page.evaluate(() => {
        window.location.reload();
      });
    }
  },

  // 商品详情页
  async productDetail() {
    let ret = null;
    let that = this;

    // 通知操作
    async function notifyFn() {
      var selector = "a.tiB2CPaidNotify";
      await that.page.waitForSelector(selector);
      const elements = await that.page.$$eval(selector, (elements) => {
        elements[2].click();
        return elements.length;
      });

      that.page.waitForTimeout(1000);

      // 数量
      const modelInput1 = await that.page.waitForSelector("#LimitTxtbx", {
        visible: true,
        timeout: 5000,
      });
      await modelInput1.focus(); //定位到搜索框
      await that.page.keyboard.type("1000");

      // 电子邮件
      const modelInput2 = await that.page.waitForSelector("#notifyEmail", {
        visible: true,
      });
      await modelInput2.focus(); //定位到搜索框
      await that.page.keyboard.type(EMAIL);

      // 点击发送
      await that.page.waitForSelector("#tiB2CPaidNotifyMe");
      await that.page.click("#tiB2CPaidNotifyMe");

      // 等待
      const finalResponse = await that.page.waitForResponse((response) =>
        response
          .url()
          .includes("https://www.ti.com.cn/store/ti/zh/tinotify/notifyEmail")
      );
      if (finalResponse && finalResponse.status() == 200) {
        console.log(finalResponse.status() + " 成功...");
      } else {
        console.log(finalResponse.status() + " 失败...");
      }

      return {
        status: finalResponse.status() == 200,
        msg:
          finalResponse.status() +
          (finalResponse.status() == 200 ? " 成功..." : " 失败..."),
      };
    }

    // 判断当前页面是否目标芯片
    async function judgeProductNum(targetP) {
      let selector = ".u-margin-right-m";
      let currentP = null;
      await that.page.waitForSelector(selector);
      currentP = await that.page.$eval(
        selector,
        (element) => element.textContent
      );

      myLog2("当前页面芯片型号：" + currentP, "red", true);
      myLog2("目标芯片型号：" + targetP, "red", true);

      await that.page.waitForTimeout(30000);
      return currentP === targetP;
    }

    // 点击跳转到首页
    async function joinHome(timeout = 1000) {
      var btn = await that.page.waitForSelector("header a");
      await that.page.waitForTimeout(timeout);
      !!btn && btn.click();
    }

    // 判断当前页面是否目标芯片，不是的话，则跳转到相应页面
    ret = await judgeProductNum(this.notifyInfo.productNum);
    if (ret) {
      // 是该芯片
      // 不做操作
    } else {
      await joinHome();
      myLog2("不是该芯片");
      return;
    }

    if (this.running) {
      myLog2("打开" + "商品详情页" + "已经打开了...", "orange", true);
      return;
    }
    this.running = true;
    myLog2("打开" + "商品详情页" + "成功...", "green", true);

    // ====================操作开始===================== //

    // 不等待配送地址和货币选择
    // this.page.waitForSelector('#target-modal-cart-page-empty-shipto-notification', {
    //   visible: true
    // });
    await that.page.waitForTimeout(10000);

    for (let i = 0; i < 3; i++) {
      myLog2(`第${i + 1}次，点击到货通知...`, "green", true);
      try {
        let obj = await notifyFn();
        ret = obj.status;
        myLog2(obj.msg, "green", true);
        if (ret) {
          break;
        }
        await that.page.waitForTimeout(1000);
      } catch (error) {
        await this.page.mouse.move(20, 20);
        await this.page.mouse.down();
        await this.page.mouse.up();
      }
    }

    // await this.page.click(selector);
    // !!btn[0] && btn[0].click();
    this.running = false;

    // 通知失败
    if (!ret) {
      let isUp = this.notifyError();
      // 失败超过最大次数则返回首页
      if (isUp) {
        this.notifyInfo = null;
        await joinHome();
      } else {
        await this.page.evaluate(() => {
          window.location.reload();
        });
      }
    } else {
      this.notifySuccess();
      // 等待一秒，点击取消掉modal
      await that.page.waitForTimeout(500);
      await this.page.mouse.move(20, 20);
      await this.page.mouse.down();
      await this.page.mouse.up();

      await joinHome();
    }
  },
};

export default obj;
